'use client'

import {
	Accordion,
	AccordionDetails,
	AccordionSummary,
	Skeleton,
	Typography
} from '@mui/material'
import Box from '@mui/material/Box'
import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { ChevronDown, SearchX } from 'lucide-react'
import React, { useEffect } from 'react'
import { toast } from 'sonner'

import { ClientCard } from '@/components/cards/client.card'
import { RequestMinCard } from '@/components/cards/min/request.min.card'

import type { IClient } from '@/types/client.types'

import { clientService } from '@/services/clients.service'
import { requestService } from '@/services/requests.service'

export function ClientDetail({ id }: { id: string }) {
	const { data, isError, error } = useQuery<IClient>({
		queryKey: ['client', id],
		queryFn: async () => await clientService.fetch(Number(id)),
		placeholderData: keepPreviousData,
		refetchOnWindowFocus: false
	})

	const requests = useQuery({
		queryKey: ['client_requests', id],
		queryFn: async () => await requestService.fetchMany(data?.requests),
		refetchOnWindowFocus: false,
		enabled: !!data?.requests
	})

	useEffect(() => {
		if (requests.isError) toast.error('Не удалось получить заявки клиента!')
	}, [requests.isError])

	return (
		<>
			{isError && (
				<Box
					sx={{
						display: 'flex',
						flexDirection: 'column',
						justifyContent: 'center',
						alignItems: 'center'
					}}
					color={'error.main'}
				>
					<SearchX size={100} />
					<Typography
						variant='h6'
						component='div'
						color='textSecondary'
					>
						{error?.message.indexOf('404')
							? 'Клиент не найден'
							: error?.message}
					</Typography>
				</Box>
			)}
			{!isError && (
				<>
					<ClientCard client_data={data} />
					{data && data.requests.length > 0 && (
						<Accordion slotProps={{ transition: { mountOnEnter: true } }}>
							<AccordionSummary expandIcon={<ChevronDown />}>
								Заявки ({data.requests.length})
							</AccordionSummary>
							<AccordionDetails>
								{requests.isPending ? (
									<Skeleton
										width={250}
										height={120}
									/>
								) : (
									requests.data?.results.map(req => (
										<RequestMinCard
											request_data={req}
											key={req.id}
										/>
									))
								)}
							</AccordionDetails>
						</Accordion>
					)}
					{data && data.contracts.length > 0 && (
						<Accordion slotProps={{ transition: { mountOnEnter: true } }}>
							<AccordionSummary expandIcon={<ChevronDown />}>
								Договоры ({data.contracts.length})
							</AccordionSummary>
							<AccordionDetails>LL</AccordionDetails>
						</Accordion>
					)}
					{data && data.orders.length > 0 && (
						<Accordion slotProps={{ transition: { mountOnEnter: true } }}>
							<AccordionSummary expandIcon={<ChevronDown />}>
								Заказы ({data.orders.length})
							</AccordionSummary>
							<AccordionDetails>LL</AccordionDetails>
						</Accordion>
					)}
				</>
			)}
		</>
	)
}
